package com.tmt.im.manager.helper;

import com.tmt.im.common.pojo.IGetKey;
import com.tmt.im.common.store.StoreSqlHelper;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.query.FieldsQueryCursor;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/9/2 18:43
 * @Version 1.0
 **/
public class IgniteQueryHelper {

    public static <K, T extends IGetKey<K>> T findOneBy(String sql, Object[] params, Class<T> clazz, IgniteCache<K, T> cache) {
        SqlFieldsQuery query = new SqlFieldsQuery(sql).setArgs(params);
        try (FieldsQueryCursor<List<?>> cursor = cache.query(query)) {
            List<T> list = new ArrayList<>();
            StoreSqlHelper.convertTo(cursor, list, clazz);
            return !CollectionUtils.isEmpty(list) ? list.get(0) : null;
        }
    }

    public static <K, T extends IGetKey<K>> List<T> findAllBy(String sql, Object[] params, Class<T> clazz, IgniteCache<K, T> cache) {
        SqlFieldsQuery query = new SqlFieldsQuery(sql).setArgs(params);
        try (FieldsQueryCursor<List<?>> cursor = cache.query(query)) {
            List<T> list = new ArrayList<>();
            StoreSqlHelper.convertTo(cursor, list, clazz);
            return list;
        }
    }

    public static <K, T extends IGetKey<K>> void executeBy(String sql, Object[] params, IgniteCache<K, T> cache) {
        SqlFieldsQuery query = new SqlFieldsQuery(sql).setArgs(params);
        try (FieldsQueryCursor<List<?>> cursor = cache.query(query)) {
            cursor.getAll();
        }
    }

    public static <K, T extends IGetKey<K>> long getCountBy(String sql, Object[] params, IgniteCache<K, T> cache) {
        SqlFieldsQuery query = new SqlFieldsQuery(sql).setArgs(params);
        try (FieldsQueryCursor<List<?>> cursor = cache.query(query)) {
            List<List<?>> result = cursor.getAll();
            if (result.size() > 0) {
                return (long) result.get(0).get(0);
            }
        }
        return 0L;
    }
}
